package org.blogwu.learn.netty学习.chapter0.nio;

import java.nio.ByteBuffer;

public class BufferReadDome {
    public static void main(String[] args) {
        // 申请堆外内存，好处时间少一次拷贝
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4);
        // allocate( 4 ); 申请堆内存，，和C申请内存很相似
        System.out.println(String.format("初始化: capacity容量：%s,position位置：%s,limit限制:%s", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit()));
        byteBuffer.put((byte) 1);
        byteBuffer.put((byte) 2);
        byteBuffer.put((byte) 3);
        {
//            byte a = byteBuffer.get();
        }
        System.out.println(String.format("写入3个字节后: capacity容量：%s,position位置：%s,limit限制:%s", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit()));
        System.out.println("开始读取");
        byteBuffer.flip();
        System.out.println(String.format("转换为读取模式后: capacity容量：%s,position位置：%s,limit限制:%s", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit()));
        {

            byte a = byteBuffer.get();
            System.out.println(a);
            a = byteBuffer.get();
            System.out.println(a);
        }
        System.out.println(String.format("读取2个字节后: capacity容量：%s,position位置：%s,limit限制:%s", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit()));
        // 清空已读取数据，注意是已读取数据
        byteBuffer.compact();
        byteBuffer.put((byte) 3);
        byteBuffer.put((byte) 4);
        byteBuffer.put((byte) 5);
        System.out.println(String.format("最终: capacity容量：%s,position位置：%s,limit限制:%s", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit()));
        {
            System.out.println("开始读取");
            byteBuffer.flip();
            byte a = byteBuffer.get();
            System.out.println(a);
            a = byteBuffer.get();
            System.out.println(a);
        }
    }
}
